import 'dart:convert';
import 'dart:async'; // 引入 async 库以使用 StreamSubscription
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:up_demo/time.dart';
import 'package:up_demo/storage_util.dart';
import 'package:up_demo/up_list.dart';
import 'package:up_demo/widget_extension.dart';
import 'cache_list.dart';
import 'multiple_choice_time.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

class Pages extends StatefulWidget {
  const Pages({super.key});

  @override
  State<Pages> createState() => _PagesState();
}

class _PagesState extends State<Pages> {
  static const String _keyPerson = 'inspection_person_name';
  static const String _keyLocation = 'inspection_location';
  static const String _keyDevice = 'inspection_device';
  static const String _keyContent = 'inspection_content';
  static const String _keyStatus = 'inspection_status';
  static const String _keyStartDate = 'inspection_start_date';
  static const String _keyEndDate = 'inspection_end_date';
  static const String _keyCachedInspections = 'cached_inspections';

  int status = 1;
  DateTime? _startDate;
  DateTime? _endDate;

  // 新增：用于存储网络状态监听的订阅
  late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;
  // 新增：当前网络连接类型
  List<ConnectivityResult> _connectionStatus = [ConnectivityResult.none];


  String get time {
    if (_startDate != null && _endDate != null) {
      return '${_startDate!.toStrYMD} - ${_endDate!.toStrYMD}';
    } else if (_startDate != null) {
      return '${_startDate!.toStrYMD} - ';
    } else if (_endDate != null) {
      return ' - ${_endDate!.toStrYMD}';
    } else {
      return '请选择时间';
    }
  }

  late TextEditingController _personController;
  late TextEditingController _locationController;
  late TextEditingController _contentController;
  late TextEditingController _deviceController;

  Future<bool> _uploadData({Map<String, dynamic>? cachedData}) async {
    final Map<String, dynamic> data;
    if (cachedData != null) {
      data = cachedData;
    } else {
      if (_personController.text.trim().isEmpty) {
        _showToast('请输入巡检人姓名');
        return false; // 返回false表示未进行上传
      }
      if (_locationController.text.trim().isEmpty) {
        _showToast('请输入巡检位置');
        return false;
      }
      if (_contentController.text.trim().isEmpty) {
        _showToast('请输入巡检内容');
        return false;
      }
      if (_startDate == null || _endDate == null) {
        _showToast('请选择巡检时间');
        return false;
      }

      data = {
        'deleted': "0",
        'endDate': _endDate!.toStrYMD,
        'inspectionContent': _contentController.text.trim(),
        'inspectionDevice': _deviceController.text.trim(),
        'inspectionLocation': _locationController.text.trim(),
        'inspectorName': _personController.text.trim(),
        'startDate': _startDate!.toStrYMD,
        'status': status,
      };
    }

    // 检查网络连接，这里使用_connectionStatus
    if (_connectionStatus.contains(ConnectivityResult.none)) {
      await _saveCachedInspection(data);
      _showToast('当前无网络，数据已保存到本地缓存。');
      if (cachedData == null) {
        _clearFormData();
      }
      return false; // 返回false表示未进行上传
    }

    try {
      final Dio dio = Dio();
      final Response response = await dio.post(
        'http://117.174.116.51:50508/api/education/inspections/add',
        data: data,
      );

      if (response.statusCode == 200) {
        _showToast('上传成功');
        if (cachedData == null) {
          _clearFormData();
        }
        return true;
      } else {
        _showToast('上传失败，状态码：${response.statusCode}');
        return false;
      }
    } on DioException catch (e) {
      _showToast('网络错误：${e.message}');
      return false;
    } catch (e) {
      _showToast('上传异常：$e');
      return false;
    }
  }

  void _showToast(String message) {
    if (!mounted) return;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: const Text('提示'),
          content: Text(message),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _saveCachedInspection(Map<String, dynamic> inspectionData) async {
    List<Map<String, dynamic>> cachedList = await _loadCachedInspections();
    cachedList.add(inspectionData);
    await StorageUtil.setString(_keyCachedInspections, jsonEncode(cachedList));
  }

  Future<List<Map<String, dynamic>>> _loadCachedInspections() async {
    String? cachedString = StorageUtil.getString(_keyCachedInspections);
    if (cachedString != null && cachedString.isNotEmpty) {
      try {
        List<dynamic> decodedList = jsonDecode(cachedString);
        return decodedList.cast<Map<String, dynamic>>();
      } catch (e) {
        print("解析缓存数据失败: $e");
        return [];
      }
    }
    return [];
  }

  Future<void> _clearCachedInspections() async {
    await StorageUtil.remove(_keyCachedInspections);
  }

  void _clearFormData() {
    setState(() {
      _personController.clear();
      _locationController.clear();
      _deviceController.clear();
      _contentController.clear();
      status = 1;
      _startDate = null;
      _endDate = null;
    });
    StorageUtil.removeAll([
      _keyPerson,
      _keyLocation,
      _keyDevice,
      _keyContent,
      _keyStatus,
      _keyStartDate,
      _keyEndDate,
    ]);
  }

  Future<void> _uploadCachedData() async {
    List<Map<String, dynamic>> cachedList = await _loadCachedInspections();
    if (cachedList.isEmpty) {
      return;
    }

    _showToast('检测到离线数据，正在尝试上传...');

    List<Map<String, dynamic>> remainingCache = [];
    for (int i = 0; i < cachedList.length; i++) {
      // 检查网络状态，确保在上传前仍然有网络
      var currentConnectivity = await (Connectivity().checkConnectivity());
      if (currentConnectivity.contains(ConnectivityResult.none)) {
        remainingCache.addAll(cachedList.sublist(i)); // 将剩余的加回
        _showToast('网络断开，暂停上传离线数据。');
        break;
      }

      bool success = await _uploadData(cachedData: cachedList[i]);
      if (!success) {
        remainingCache.add(cachedList[i]); // 如果失败，将其添加到剩余缓存中
      }
    }

    // 更新本地缓存
    if (remainingCache.length < cachedList.length) { // 如果有任何数据成功上传
      await StorageUtil.setString(_keyCachedInspections, jsonEncode(remainingCache));
      if (remainingCache.isEmpty) {
        _showToast('所有离线数据已成功上传。');
      } else {
        _showToast('部分离线数据已成功上传，剩余 ${remainingCache.length} 条待上传。');
      }
    } else if (remainingCache.isNotEmpty && remainingCache.length == cachedList.length) {
      _showToast('未能上传任何离线数据，请检查网络。');
    }
  }

  @override
  void initState() {
    super.initState();

    _personController = TextEditingController();
    _locationController = TextEditingController();
    _contentController = TextEditingController();
    _deviceController = TextEditingController();

    _loadSavedData();

    _personController.addListener(() {
      StorageUtil.setString(_keyPerson, _personController.text);
    });
    _locationController.addListener(() {
      StorageUtil.setString(_keyLocation, _locationController.text);
    });
    _deviceController.addListener(() {
      StorageUtil.setString(_keyDevice, _deviceController.text);
    });
    _contentController.addListener(() {
      StorageUtil.setString(_keyContent, _contentController.text);
    });

    // 1. 初始化时获取当前网络状态
    Connectivity().checkConnectivity().then((result) {
      setState(() {
        _connectionStatus = result;
      });
      // 首次进入页面如果有网络，尝试上传缓存数据
      if (!_connectionStatus.contains(ConnectivityResult.none)) {
        _uploadCachedData();
      }
    });

    // 2. 启动网络状态监听
    _connectivitySubscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      setState(() {
        _connectionStatus = result;
      });
      // 当网络从无到有变化时，尝试上传缓存数据
      if (!result.contains(ConnectivityResult.none)) {
        _uploadCachedData();
      } else {
        _showToast('网络连接已断开！');
      }
    });
  }

  void _loadSavedData() {
    _personController.text = StorageUtil.getString(_keyPerson) ?? '';
    _locationController.text = StorageUtil.getString(_keyLocation) ?? '';
    _deviceController.text = StorageUtil.getString(_keyDevice) ?? '';
    _contentController.text = StorageUtil.getString(_keyContent) ?? '';

    status = StorageUtil.getInt(_keyStatus) ?? 1;

    final String? startDateString = StorageUtil.getString(_keyStartDate);
    if (startDateString != null) {
      _startDate = DateTime.tryParse(startDateString);
    }
    final String? endDateString = StorageUtil.getString(_keyEndDate);
    if (endDateString != null) {
      _endDate = DateTime.tryParse(endDateString);
    }
  }

  @override
  void dispose() {
    _personController.dispose();
    _locationController.dispose();
    _contentController.dispose();
    _deviceController.dispose();
    _connectivitySubscription.cancel(); // 取消网络监听订阅
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF4F9FD),
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          '巡检上传',
          style: TextStyle(
            color: Color(0xFF333333),
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: const Color(0xFFffffff),
        actions: [
          TextButton(onPressed: () {
            if(_connectionStatus.contains(ConnectivityResult.none)) {
              showDialog(
                context: context,
                builder: (context) {
                  return CupertinoAlertDialog(
                    title: const Text('提示'),
                    content: const Text('当前无网络连接，点击进入本地缓存列表'),
                    actions: [
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: const Text('取消'),
                      ),
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) => CacheList()));
                        },
                        child: const Text('进入列表'),
                      ),
                    ],
                  );
                },
              );
            } else {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) => UpListPage()));
            }
          }, child: const Text('上传列表'))
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            children: [
              TextField(
                controller: _personController,
                decoration: InputDecoration(
                  labelText: '请输入巡检人姓名',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _locationController,
                decoration: InputDecoration(
                  labelText: '请输入当前巡检位置',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _deviceController,
                decoration: InputDecoration(
                  labelText: '请输入巡检设备',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _contentController,
                decoration: InputDecoration(
                  labelText: '请输入巡检内容',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                ),
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  const Text('巡检状态'),
                  RadioMenuButton(
                    value: 1,
                    groupValue: status,
                    onChanged: (value) {
                      if (value != null) {
                        setState(() {
                          status = value;
                        });
                        StorageUtil.setInt(_keyStatus, status);
                      }
                    },
                    child: const Text('有问题'),
                  ),
                  RadioMenuButton(
                    value: 2,
                    groupValue: status,
                    onChanged: (value) {
                      if (value != null) {
                        setState(() {
                          status = value;
                        });
                        StorageUtil.setInt(_keyStatus, status);
                      }
                    },
                    child: const Text('没有问题'),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              const Align(
                alignment: Alignment.centerLeft,
                child: Text('巡检时间:'),
              ),
              GestureDetector(
                onTap: () {
                  DateRangePicker.show(
                    context: context,
                    initialStartDate: _startDate ?? DateTime.now().subtract(const Duration(days: 15)),
                    initialEndDate: _endDate ?? DateTime.now(),
                    minDate: DateTime.now().subtract(const Duration(days: 365)),
                    maxDate: DateTime.now(),
                    onStartEndConfirm: (DateTime start, DateTime end) {
                      setState(() {
                        _startDate = start;
                        _endDate = end;
                      });
                      StorageUtil.setString(_keyStartDate, _startDate!.toIso8601String());
                      StorageUtil.setString(_keyEndDate, _endDate!.toIso8601String());
                    },
                  );
                },
                child: Container(
                  height: 45,
                  margin: const EdgeInsets.symmetric(
                    vertical: 8,
                  ),
                  alignment: Alignment.centerLeft,
                  padding: const EdgeInsets.only(left: 16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(color: const Color(0xFFDCDCDC)),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(time),
                ),
              )
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        height: 45,
        margin: const EdgeInsets.all(16),
        width: double.infinity,
        alignment: Alignment.center,
        decoration: BoxDecoration(color: Colors.blue, borderRadius: BorderRadius.circular(8)),
        child: const Text(
          '提交',
          style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
        ),
      ).click(() {
        _uploadData();
      }),
    );
  }
}